package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dtos.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.IHistoryService;
import com.heima.utils.threadlocal.ApThreadLocal;
import com.mongodb.client.result.DeleteResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class HistoryServiceImpl implements IHistoryService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存历史记录
     *
     * @param keyword
     * @param userId
     */
    @Async
    @Override
    public void saveHistoryToMongo(String keyword, Long userId) {
        //1.根据用户id和关键字去查询mongo
        Query query=Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2.如果存在，则更新最新时间，然后直接返回
        if(apUserSearch!=null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //3. 如果不存在，开始执行以下代码
            //3.1 根据当前用户下查看是否包含数据超过10条
        List<ApUserSearch> userSearchList = mongoTemplate.find(
                Query.query(Criteria.where("userId").is(userId)) //条件查询
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))//排序
                , ApUserSearch.class);


        //3.1. 封装最新的数据
        ApUserSearch newUserSearc=new ApUserSearch();
        newUserSearc.setUserId(userId.intValue());
        newUserSearc.setKeyword(keyword);
        newUserSearc.setCreatedTime(new Date());
        newUserSearc.setId(ObjectId.get().toHexString());


        //3.2 如果超过10条，则替换最后一条，也插入到mongo中
        if(userSearchList!=null && userSearchList.size()>10){
            //1.获取最后一条
            ApUserSearch userSearch = userSearchList.get(userSearchList.size() - 1);
            /**
             *  3.替换最后一条
             *  参数1 表示查询条件,表示查询到原来的旧数据
             *  参数2表示要替换的元素信息，新数据
             */
            mongoTemplate.findAndReplace(
                    Query.query(Criteria.where("id").is(userSearch.getId())),
                    newUserSearc);
            return;

        }
        //3.3 如果没有超过，则直接插入到mongo中
        mongoTemplate.insert(newUserSearc);
    }

    /**
     * 查询历史记录
     *
     * @return
     */
    @Override
    public ResponseResult list() {

        ApUser apUser = ApThreadLocal.getApUser();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1.根据用户id进行倒序展示
        Query query=Query.query(
                Criteria.where("userId").is(apUser.getId()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApUserSearch> userSearchList = mongoTemplate.find(query, ApUserSearch.class);
        if(userSearchList==null || userSearchList.size()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return ResponseResult.okResult(userSearchList);
    }

    /**
     * 删除
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult removeHistory(HistorySearchDto dto) {
        ApUser apUser = ApThreadLocal.getApUser();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        DeleteResult result = mongoTemplate.remove(
                Query.query(Criteria.where("userId").is(apUser.getId()).and("id").is(dto.getId()))
                , ApUserSearch.class);
        boolean flag = result.wasAcknowledged();
        if(!flag){
            return ResponseResult.okResult("删除失败");
        }
        return ResponseResult.okResult("删除成功");
    }
}
